package com.hk.alipay.security;

import com.hk.core.authentication.api.UserPrincipal;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;

import java.io.Serializable;
import java.util.Collection;

/**
 * 支付宝
 *
 * @author Kevin
 */
public class AliPayAuthenticationToken extends AbstractAuthenticationToken {

    private final Object principal;

    public AliPayAuthenticationToken(Serializable principal) {
        super(null);
        this.principal = principal;
        setAuthenticated(false);
    }

    public AliPayAuthenticationToken(Serializable principal, Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.principal = principal;
        super.setAuthenticated(true);
    }

    @Override
    public void setAuthenticated(boolean authenticated) {
        if (authenticated) {
            throw new IllegalArgumentException(
                    "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
        }
        super.setAuthenticated(false);
    }

    @Override
    public Object getCredentials() {
        return null;
    }

    @Override
    public String getName() {
        var p = getPrincipal();
        return (p instanceof UserPrincipal userPrincipal) ?
                userPrincipal.getAccount() : super.getName();
    }

    @Override
    public Object getPrincipal() {
        return principal;
    }

    @Override
    public boolean equals(Object obj) {
        if (!super.equals(obj)) {
            return false;
        }
        if (obj instanceof AliPayAuthenticationToken token) {
            return this.principal.equals(token.principal);
        }
        return false;
    }

    @Override
    public int hashCode() {
        int result = super.hashCode();
        result = 31 * result + this.principal.hashCode();
        return result;
    }
}
